package cn.knightzz.auth;

import cn.hutool.core.util.StrUtil;
import cn.knightzz.service.SysUserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理注销请求
 *
 * @author knightzz
 * @date 2021/4/11 15:12
 */
@Component("myLogoutHandler")
public class MyLogoutHandler implements LogoutHandler {

    private static SysUserService sysUserService;

    @Resource
    public void setSysUserService(SysUserService sysUserService) {
        MyLogoutHandler.sysUserService = sysUserService;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // 获取token
        String token = request.getHeader("Authorization");
        if (!StrUtil.isEmpty(token)) {
            // 清理
            // 将token从数据库中删除
            sysUserService.deleteToken(token);
            SecurityContextHolder.clearContext();
        }
    }
}